//
//  WeightedRandomTextGenerator.m
//  HelloIphone
//
//  Created by Geoffrey Gallaway on 12/18/08.
//

#import "WeightedRandomTextGenerator.h"
#import <Foundation/NSArray.h>


@implementation WeightedRandomTextGenerator

@synthesize originalCharacterList;
@synthesize weightedRandomCharacterList;


- (id) initWithCharacterList:(NSArray *) characterArray {
//	expandedCharacterList = [[NSMutableArray alloc] init];
	characterWeightValues = [[NSMutableArray alloc] init];
	originalCharacterList = characterArray;
	for (int i = 0; i < [characterArray count]; i++) {
		//NSLog([characterArray objectAtIndex:i]);
	}
	return self;
}

- (void) buildWeightedItemList:(UInt32) length {
	int maxScore = 0;
	NSMutableArray *weightedList = [[NSMutableArray alloc] initWithCapacity:10];
	for (int i = 0; i < [originalCharacterList count]; i++) {

		int score = (i * i) + 2;
		[characterWeightValues addObject:[NSNumber numberWithInt:score]];
		if (maxScore < score) {
			maxScore = score;
		}
	}
	int previousValue = 0;
	for (int i = 0; i < length; i++) {
		int randomScore = rand() % maxScore;
		for (int p = 0; p < [characterWeightValues count]; p++) {
			NSNumber *characterWeightValuesItem = [characterWeightValues objectAtIndex:p];
			if (randomScore <= [characterWeightValuesItem intValue] && randomScore > previousValue) {
				[weightedList addObject:[originalCharacterList objectAtIndex:p]];
				previousValue = [characterWeightValuesItem intValue];
				continue;
			}
			previousValue = [characterWeightValuesItem intValue];
		}
		
	}
	weightedRandomCharacterList = weightedList;
	
}

@end
